package com.example.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {
    public  static  void  main(String[] args) throws IOException {
        //设置Url和端口， 127.0.0.1代表本机
        String url = "127.0.0.1";
        int port = 6666;
        //与服务端建立连接
        Socket socket = new Socket(url,port);
        System.out.println("已经连接到服务端");
        //建立连接后输出流到服务端
        OutputStream outputStream = socket.getOutputStream();
        String message = "Hello,666";
        outputStream.write(message.getBytes("UTF-8"));

        //告诉服务器已发送完毕
        socket.shutdownOutput();
        //接受服务器返回的消息
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, 0, len,"UTF-8"));
        }
        System.out.println("来自服务器的消息: " + sb);
        inputStream.close();

        outputStream.close();
        socket.close();
    }

}
